import 'dart:async';

import 'package:baidu_map/utils/log_util.dart';
import 'package:baidu_map/utils/map_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';

class SeriesLocationPage extends StatefulWidget {
  const SeriesLocationPage({Key? key}) : super(key: key);

  @override
  State<SeriesLocationPage> createState() => _SeriesLocationPageState();
}

class _SeriesLocationPageState extends State<SeriesLocationPage> {

  BaiduLocation? _locationResult;
  StreamSubscription? _listener;
  late BMFMapController _myMapController;



  @override
  void initState() {
    super.initState();
    
    _listener = MapUtils().propertyListener?.onChanged.listen((newValue) {
      setState(() {
        _locationResult = newValue;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _listener?.cancel();
    MapUtils().stopSeriesLocation();
  }

  void locationFinish() {
    BMFMarker marker = BMFMarker.icon(
      position: BMFCoordinate(
        _locationResult?.latitude ?? 0.0,
        _locationResult?.longitude ?? 0.0
      ),
      title: 'flutterMarker',
      identifier: "flutter_marker",
      icon: 'resoures/icon_mark.png'
    );

    _myMapController.addMarker(marker);
    _myMapController.setCenterCoordinate(
      BMFCoordinate(
          _locationResult?.latitude ?? 0.0,
          _locationResult?.longitude ?? 0.0
      ),
      false
    );
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> resultWidgets = [];

    if(_locationResult?.locTime != null) {
      _locationResult?.getMap().forEach((key, value) {
        resultWidgets.add(_resultWidget(key, value));
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('单次定位'),
      ),
      body: Stack(
        children: [
          Positioned(
            child: _createMapContainer(),
          ),
          Container(height: 20),
          SizedBox(
            height: MediaQuery.of(context).size.height - 500,
            child: ListView(
              children: resultWidgets,
            ),
          ),
          _createButtonContainer()
        ],
      ),
    );
  }

  Widget _createMapContainer() {
    return SizedBox(
      height: 300,
      child: BMFMapWidget(
        onBMFMapCreated: (controller) {
          onBMFMapCreated(controller);
        },
        mapOptions: initMapOptions(),
      ),
    );
  }

  Widget _createButtonContainer() {
    return Container(
      alignment: Alignment.bottomCenter,
      child: ElevatedButton(
        onPressed: () {
          MapUtils().startLocation(timeOut: 3000);
        },
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.blueAccent),
          overlayColor: MaterialStateProperty.all(Colors.yellow),
          shape: MaterialStateProperty.all(RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5)
          ))
        ),
        child: const Text('开始定位'),
      ),
    );
  }

  Widget _resultWidget(key,value) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('$key:' ' $value')
        ],
      ),
    );
  }

  BMFMapOptions initMapOptions() {
    return BMFMapOptions(
      center: BMFCoordinate(
        39.917215,
        116.380341
      ),
      zoomLevel: 12,
      mapPadding: BMFEdgeInsets(top: 0, left: 0, right: 0, bottom: 0)
    );
  }

  void onBMFMapCreated(BMFMapController controller) {
    _myMapController = controller;
    _myMapController.setMapDidLoadCallback(callback: () {
      LogUtil.i('mapDidLoad-地图加载完成');
    });
  }
}
